<template>
  <div class="page-container">
    <!-- 加载动画 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <div class="loading-text">加载中，请稍候...</div>
    </div>

    <div class="project-table" v-if="!loading">
      <div class="table-header">
        <div style="display: flex; align-items: center;">
          <div class="table-title">留资数据</div>
        </div>
        
        <div class="table-actions" style="display: flex;">
          <div style="display: flex; align-items: center;">
            <div style="margin-left: 20px;color: #606266; font-size: 15px;">按条件筛选：</div>
          <el-select
            v-model="selectedHeaderKey"
            placeholder="选择筛选项"
            class="date-select ml-2"
            style="width: 180px; margin-left: 8px;"
          >
            <el-option
              v-for="header in headersVal"
              :key="header.key"
              :label="header.header || header.key"
              :value="header.key"
            />
          </el-select>
          <!-- 条件显示的搜索框 -->
          <transition name="fade-in" mode="out-in">
            <div v-if="selectedHeaderKey" key="search-container" style="display: inline-flex; align-items: center;">
              <el-input
                v-model="searchValue"
                clearable
                placeholder="请输入搜索内容"
                class="date-select ml-2"
                style="width: 180px; height: 36.5px; border: none; margin-left: 8px;"
                size="large"
                @input="getSeachConnect"
              >
              </el-input>
              <el-button
                type="primary"
                size="large"
                style="margin-left: 8px; margin-right: 18px; height: 35px;background: linear-gradient(135deg, #1e5799 0%, #2989d8 100%);"
                @click="handleSearch"
              >
                搜索
              </el-button>
            </div>
          </transition>
            <span style="margin-right: 8px; color: #606266; font-size: 15px;">按日期筛选：</span>
            <el-select
              v-model="date"
              placeholder="筛选单日数据"
              clearable
              class="date-select"
              @change="handleDateChange"
            >
              <!-- 添加全部日期选项 -->
              <el-option
                key="all"
                label="全部日期"
                value=""
              />
              <!-- 原有日期选项 -->
              <el-option
                v-for="dateItem in dateOptions"
                :key="dateItem"
                :label="dateItem"
                :value="dateItem"
              />
            </el-select>
          </div>
          <div class="create-button" @click="exportActivityData">导出数据</div>
        </div>
      </div>

      <el-scrollbar style="width: 100%;overflow-x: auto; white-space: nowrap;">
        <el-table
          :data="paginatedData"
          style="width: 100%"
          :header-cell-style="{
            'text-align': 'center',
            height: '50px',
            color: '#999999',
            'font-size': '13.5px',
            'white-space': 'nowrap'
          }"
          :cell-style="{
            'text-align': 'center',
            height: '45px',
            'white-space': 'nowrap'
          }"
          :min-width="columnsList.length * 150"
        >
          <template v-for="(item, index) in columnsList" :key="index">
            <el-table-column
              v-if="!item.key.includes('_complete')"
              :prop="item.key"
              :label="item.header"
              align="center"
              width="230"
            ></el-table-column>
            <el-table-column
              v-if="item.key.includes('_complete')"
              :prop="item.key"
              :label="item.header"
              align="center"
            >
              <template #default="scope">
                <el-tag :type="scope.row[item.key] == 1 ? 'success' : 'info'">
                  {{ scope.row[item.key] == 1 ? "已核销" : "未核销" }}
                </el-tag>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </el-scrollbar>
      <div class="pagination-container">
        <el-pagination
          background
          :current-page="currentPage"
          :page-size="pageSize"
          :total="verificationList.length"
          layout="prev, pager, next, jumper"
          @current-change="currentPage = $event"
        />
      </div>
    </div>

    <!-- 空数据界面 - 数据为空且非加载时显示 -->
    <!-- <div v-else-if="!loading" class="no-data-container">
      <div class="no-data-icon">📊</div>
      <div class="no-data-text">暂无留资数据</div>
      <div class="no-data-subtext">当前活动暂无相关留资记录</div>
    </div> -->

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import { saveAs } from "file-saver";
import http from "@/libs/http";
import { useRoute } from "vue-router";
const route = useRoute();

const verificationList = ref([]);
const currentPage = ref(1);
const pageSize = 50;
const date = ref(''); // 已存在的日期变量
const dateOptions = ref([]); // 新增日期选项数组
const selectedHeaderKey = ref('');
const searchValue = ref(''); // 添加搜索框绑定变量
const headersVal = ref([]);

const totalPages = computed(() =>
  Math.ceil(verificationList.value.length / pageSize)
);

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize;
  return verificationList.value.slice(start, start + pageSize);
});
const loading = ref(false);

let columnsList = ref([]);
let newColumnsList = ref({}); //重新组装一下，变成对象字典

// 请求接口获取留资数据
async function fetchRetentionData() {
  try {
    const param = {
      token: localStorage.getItem("openid"),
      activity_id: Number(route.query.site),
      page: 0,
      date: date.value,
    };
    loading.value = true;
    const response = await http.$post(
      "/hd_project/Backend/exportActivityData",
      param
    );
    if (response.code == 200) {
      loading.value = false;
      let { headers, cluelist } = response.data;
      columnsList.value = headers;
      // 变成对象字典
      newColumnsList.value = columnsList.value.reduce((acc, cur) => {
        acc[cur.key] = cur.header;
        return acc;
      }, {});

      verificationList.value = cluelist;
      localStorage.setItem('cachedCluelist', JSON.stringify(cluelist));
      currentPage.value = 1;
      headersVal.value = headers
      console.log(headersVal.value,"拿到数据了", newColumnsList);
    } else {
      loading.value = false;
      console.log("没拿到数据");
    }
  } catch (error) {
    loading.value = false;
    ElMessage.error("获取留资数据失败");
  }
}

const getSeachConnect = (e) => {
  searchValue.value = e
  // 当输入为空时，加载全部缓存数据
  if (!e || e.trim() === '') {
    const cachedCluelist = JSON.parse(localStorage.getItem('cachedCluelist') || '[]');
    verificationList.value = cachedCluelist;
  }
}

const handleSearch = () => {
  // 获取本地缓存
  const cachedCluelist = JSON.parse(localStorage.getItem('cachedCluelist') || '[]');
  // 添加空值判断和提示
    if (!selectedHeaderKey.value || !searchValue.value.trim()) {
      ElMessage.warning('请选择筛选项并输入搜索内容');
      return;
    }

    // 循环过滤数组，查找匹配项
  const filteredList = cachedCluelist.filter(item => {
    const key = selectedHeaderKey.value;
    const value = item[key];
    
    // 核销状态特殊处理（匹配表格显示逻辑）
    if (key.includes('_complete')) {
      // 将数值状态转换为表格显示的文本
      const statusText = value === 1 ? '已核销' : '未核销';
      return statusText.toLowerCase().includes(searchValue.value.trim().toLowerCase());
    }
    
    // 普通字段处理逻辑
    return value !== undefined && value !== null && 
           String(value).toLowerCase().includes(searchValue.value.trim().toLowerCase());
  });
  
  // console.log('过滤结果:', filteredList);
  // 可以在这里使用过滤后的数组，例如更新表格数据
  verificationList.value = filteredList;
}



// 导出数据
const exportActivityData = () => {
  import("xlsx").then((XLSX) => {
    try {
      const ws = XLSX.utils.json_to_sheet(
        verificationList.value.map((item) => ({
          ...Object.keys(newColumnsList.value).reduce((acc, key) => {
            const value = item[key];

            // 通用字段处理器
            switch (true) {
              case key === "phone":
                acc[newColumnsList.value[key]] = String(value).replace(
                  /(\\d{3})\\d{4}(\\d{4})/,
                  "$1****$2"
                );
                break;
              case key.includes("_starttime") || key === "verifyTime":
                acc[newColumnsList.value[key]] = dayjs(value).isValid()
                  ? dayjs(value).format("YYYY-MM-DD HH:mm")
                  : "-";
                break;
              case key.endsWith("_complete") || key === "status":
                acc[newColumnsList.value[key]] =
                  value === 1 ? "已核销" : "未核销";
                break;
              default:
                acc[newColumnsList.value[key]] = value || "-";
            }
            return acc;
          }, {}),
        }))
      );

      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "核销记录");

      // 设置列宽
      ws["!cols"] = [
        { wch: 15 },
        { wch: 12 },
        { wch: 8 },
        { wch: 15 },
        { wch: 20 },
        { wch: 10 },
      ];

      const wbout = XLSX.write(wb, { type: "array", bookType: "xlsx" });
      saveAs(
        new Blob([wbout], { type: "application/octet-stream" }),
        `核销记录_${dayjs().format("YYYYMMDD_HHmm")}.xlsx`
      );
    } catch (e) {
      ElMessage.error("导出失败：" + e.message);
    }
  });
};

const getActivityList = async () => {
  try {
    let param = {
      token: localStorage.getItem("openid"),
    }
    // 发送POST请求获取站点列表
    const response = await http.$post('/hd_project/Backend/getActivityList', param);
    // 假设接口返回格式为 { code: 200, data: [...] }
    if (response.code === 200) {
      // 将获取的数据赋值给列表变量（假设为activityList）
      let siteId = Number(route.query.site)
      // 根据siteId匹配数组中对应的数据项
      const matchedItem = response.data.find(item => item.id === siteId);
       console.log('>>>>>>>>>', matchedItem)
      if (matchedItem && matchedItem.startdate && matchedItem.enddate) {
        const dateArray = generateDateArray(matchedItem.startdate, matchedItem.enddate);
        console.log('生成的日期数组:', dateArray);
        nextTick(() => {
          dateOptions.value = dateArray;
          // 设置默认日期为当天（若存在）
          const today = new Date().toISOString().split('T')[0];
          date.value = dateOptions.value.includes(today) ? today : '';
        });
        // 可将结果赋值给响应式变量，例如：dateList.value = dateArray;
      }
    } else {
      // 处理接口返回错误
      ElMessage.error('获取站点列表失败: ' + response.msg);
    }
  } catch (error) {
    // 处理网络错误
    ElMessage.error('请求失败，请检查网络连接');
  } finally {
  }
}

// 生成日期数组的工具函数
const generateDateArray = (startDateStr, endDateStr) => {
  const dateArray = [];
  const startDate = new Date(startDateStr);
  const endDate = new Date(endDateStr);

  // 验证日期有效性
  if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
    console.error('无效的日期格式');
    return dateArray;
  }

  // 确保开始日期不大于结束日期
  if (startDate > endDate) {
    [startDate, endDate] = [endDate, startDate];
  }

  // 循环生成日期
  const currentDate = new Date(startDate);
  while (currentDate <= endDate) {
    // 格式化为 YYYY-MM-DD
    const dateStr = currentDate.toISOString().split('T')[0];
    dateArray.push(dateStr);
    // 增加一天
    currentDate.setDate(currentDate.getDate() + 1);
  }

  return dateArray;
};

// 日期变更处理函数
const handleDateChange = () => {
  // 重新获取数据刷新列表
  fetchRetentionData();
};

// 初始化
onMounted(() => {
  getActivityList().then(() => {
    fetchRetentionData();
  })
});
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin: 26px 34px;
  margin-top: 81px;
  padding: 12px;
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

@media (max-width: 768px) {
  .pagination-container {
    margin: 12px;
    justify-content: center;
  }
}

/* 修改项目表格容器为相对定位 */
.project-table {
  position: relative; /* 添加相对定位作为遮罩的参照物 */
  width: 98%;
  min-height: 20vh;
  margin: 30px auto;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 修改遮罩为绝对定位并覆盖整个容器 */
.loading-overlay {
  position: absolute; /* 改为绝对定位，相对于.project-table */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10; /* 确保覆盖表格内容但不影响页面其他元素 */
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f8fafc;
  border-bottom: 1px solid #ebeef5;
}
.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.page-container {
  position: relative;
  min-height: 78vh;
  padding: 20px;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3a7bb8;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.loading-text {
  font-size: 16px;
  color: #3a7bb8;
}

.create-button {
  margin-left: 12px;
  background: var(--el-color-primary);
  background: linear-gradient(135deg, #1e5799 0%, #2989d8 100%);
  border: none;
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.create-button:hover {
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(41, 137, 216, 0.3);
}

.create-icon {
  margin-right: 6px;
}

/* 空数据样式 */
.no-data-container {
  min-height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin: 20px 0;
  padding: 40px;
}

.no-data-icon {
  font-size: 64px;
  color: #c0c4cc;
  margin-bottom: 20px;
  animation: float 3s ease-in-out infinite;
}

.no-data-text {
  font-size: 18px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.no-data-subtext {
  font-size: 14px;
  color: #909399;
}

/* 浮动动画 */
@keyframes float {
  0% { transform: translateY(0px); }
  50% { transform: translateY(-15px); }
  100% { transform: translateY(0px); }
}

::v-deep .date-select {
  background: linear-gradient(135deg, #99d6ff 0%, #4da6ff 100%);
  border: none;
}
.date-select {
  padding: 2px;
  border-radius: 4px;
  width: 200px;
  margin-right: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.fade-in-enter-from {
  opacity: 0;
  transform: translateY(10px);
}
.fade-in-enter-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}
.fade-in-enter-to {
  opacity: 1;
  transform: translateY(0);
}
</style>
